package com.tledu.zyf.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tledu.zyf.model.User;
import com.tledu.zyf.service.IUserService;
import com.tledu.zyf.util.AjaxObj;
import com.tledu.zyf.util.ObjectFactory;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
//	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 解决中文乱码
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 获取前端页面提交的账号密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		// 封装到 user 对象中
		User user = new User(username, password);

		// 接口指向子类实现
		// ObjectFactory 是一个工厂类
		IUserService userService = ObjectFactory.getUserService();
		// pw 用来给前端数据
		PrintWriter pw = response.getWriter();
		try {
			// 登录成功 返回对象
			User loginUser = userService.login(user);
			// 保存到 session 中
			request.getSession().setAttribute("loginUser", loginUser);
//			pw.println("{'id':1,'msg':'登陆成功'}");
			pw.println(new AjaxObj(1, "登陆成功").toJSON());
		} catch (Exception e) {
			// 能到这里 说明登录失败
			String msg = e.getMessage();
			pw.println(new AjaxObj(0, msg).toJSON());
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
